package controller;

import bean.dto.Dto;
import bean.pojo.GdOrder;
import bean.vo.OrderVo;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import service.GdOrderService;
import service.TokenService;
import utils.DtoUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
public class TradeController {
    @Resource
    private TokenService tokenService;
    @Resource
    private GdOrderService gdOrderService;
    /**
     * 支付
     */
    @RequestMapping(value = "/aliPay",method = RequestMethod.POST)
    public void aliPay(HttpServletRequest request,
                                    @RequestBody OrderVo orderVo,
                                    HttpServletResponse response){
        String token = request.getHeader("token");
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","2016091600524332",
                "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCOrAPvb1TjJ6xCusp4FZkeiSxw0Pk92/II/8URjggVrYIDtWuk80KJoZaAs2dX5UL/G1jMqZ6pHuhTVh6p17+EFifhmrrbsMmelVs8hyb01gv+0gqIkTqCv5gxgrdM/mCGoNEd31oiO26tPDxvu7T2XvTr7SBQW1wmS/Gumc8H9+Iu4rDlX5dt2rc3g8qDOGZnapEc51GLBHo/ts1I3UDximr5TzgO6fHRbE9V0QOJUrg69TrVwqDQjvp9UyuYtUVnbToQlhUUlx+meJoVXNFiZrZq3HJLbDH1GMEK0geskvJ/RQgRZxpOLl83e/PSwC8uH1MnJSOkcfl3JMYfpZn9AgMBAAECggEAe8lnyLDR+B0N6v/id/pVVhcyhdfqyO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+apvniNxz0qugqGyP6tYxYrwaRC4q9thrMcqld/d3bQSVMc+6ZV8eODW7VTDoBKDhMxHWK3rYW4IMGnQfj8l9l2pJM8/xUVJp1RrvpV7DRRyXCF9e4cOlBWx6qnP",
                "json","UTF-8",
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0PS+O+IydPyJLXTsgRT68hjxcA+EHlENiHNS4y+S2g3AeJfPHfo7HXfUen+qEZIGZk6GBnMTdu1ow8ZCoIqB2eCbWp/+7XOY9TK+jDo9my2TOpYGQTN5eZyVU2DdcumKpyeuG5tsaUU5skdpmC7/02a0s1+wBH0yN6ifp6LjDJxbohJN7fbL+HFZKONkqWfJjADR40Qnk1a5Z9eL6PNRkb/clSEFEYu+PTRGopqa9j+wh4V79EXyZTICH0JTK0mf/90MNltQ6f5Eoq7KaKOZeJXW7JIyWB4eCUXjWetg1NIsniTJuTH7glIt7dzSwoKp72P7vXAXmmU5JGJ0efjvSQIDAQAB",
                "RSA2");
        try {
            if (tokenService.validate(request.getHeader("user-agent"),token)){
                //TODO 调用订单服务增加数据和更新
                GdOrder order = new GdOrder();
                order.setTradeIncome(orderVo.getMoney());
                order.setTradePay(orderVo.getMoney());
                order.setTradePayment(orderVo.getTradePayment());
                order.setTradeService(orderVo.getTradeService());
                order.setTradeNo(orderVo.getTradeNo());
                order.setTradeState(0);
                gdOrderService.insert(order);
                //TODO 调用支付宝支付
                AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
                alipayRequest.setReturnUrl("http://domain.com/CallBack/return_url.jsp");
                alipayRequest.setNotifyUrl("http://domain.com/CallBack/notify_url.jsp");//在公共参数中设置回跳和通知地址
                alipayRequest.setBizContent("{" +
                        "    \"out_trade_no\":"+orderVo.getTradeNo()+"," +
//                        "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                        "    \"total_amount\":"+orderVo.getMoney()+"," +
//                        "    \"subject\":\"Iphone6 16G\"," +
//                        "    \"body\":\"Iphone6 16G\"," +
                        "    \"service\":\""+orderVo.getTradeService()+"\"," +
                        "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
                        "    \"extend_params\":{" +
                        "    \"sys_service_provider_id\":\"2088511833207846\"" +
                        "    }"+
                        "  }");//填充业务参数
                String form="";
                try {
                    form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
                } catch (AlipayApiException e) {
                    e.printStackTrace();
                }
                response.setContentType("text/html;charset=" + "UTF-8");
                response.getWriter().write(form);//直接将完整的表单html输出到页面
                response.getWriter().flush();
                response.getWriter().close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 同步回调
     */
    @RequestMapping(value = "/return", method = RequestMethod.POST)
    public @ResponseBody Dto returnUrl(HttpServletRequest request){
        try{
            //获取支付宝GET过来反馈信息
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }

            boolean signVerified = AlipaySignature.rsaCheckV1(params,"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0PS+O+IydPyJLXTsgRT68hjxcA+EHlENiHNS4y+S2g3AeJfPHfo7HXfUen+qEZIGZk6GBnMTdu1ow8ZCoIqB2eCbWp/+7XOY9TK+jDo9my2TOpYGQTN5eZyVU2DdcumKpyeuG5tsaUU5skdpmC7/02a0s1+wBH0yN6ifp6LjDJxbohJN7fbL+HFZKONkqWfJjADR40Qnk1a5Z9eL6PNRkb/clSEFEYu+PTRGopqa9j+wh4V79EXyZTICH0JTK0mf/90MNltQ6f5Eoq7KaKOZeJXW7JIyWB4eCUXjWetg1NIsniTJuTH7glIt7dzSwoKp72P7vXAXmmU5JGJ0efjvSQIDAQAB",
                    "UTF-8", "RSA2"); //调用SDK验证签名

            //——请在这里编写您的程序（以下代码仅作参考）——
            if(signVerified) {
                //商户订单号
                String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

                //支付宝交易号
                String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

                //付款金额
                String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

//                out.println("trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);
                return DtoUtil.returnSuccess();
            }else {
                return DtoUtil.returnFail("error","验签失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            return DtoUtil.returnFail("error","验签失败");
        }
    }
    /**
     * 异步回调
     */
    @RequestMapping(value = "/notify", method = RequestMethod.POST)
    public @ResponseBody Dto trackPaymentStatus(HttpServletRequest request,
                           HttpServletResponse response){
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            try {
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            params.put(name, valueStr);
        }

        boolean signVerified = false; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0PS+O+IydPyJLXTsgRT68hjxcA+EHlENiHNS4y+S2g3AeJfPHfo7HXfUen+qEZIGZk6GBnMTdu1ow8ZCoIqB2eCbWp/+7XOY9TK+jDo9my2TOpYGQTN5eZyVU2DdcumKpyeuG5tsaUU5skdpmC7/02a0s1+wBH0yN6ifp6LjDJxbohJN7fbL+HFZKONkqWfJjADR40Qnk1a5Z9eL6PNRkb/clSEFEYu+PTRGopqa9j+wh4V79EXyZTICH0JTK0mf/90MNltQ6f5Eoq7KaKOZeJXW7JIyWB4eCUXjWetg1NIsniTJuTH7glIt7dzSwoKp72P7vXAXmmU5JGJ0efjvSQIDAQAB\n" +
                            "sentinel",
                    "UTF-8", "RSA2");
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return DtoUtil.returnFail("error","AlipayApiException");
        }

        //——请在这里编写您的程序（以下代码仅作参考）——

	/* 实际验证过程建议商户务必添加以下校验：
	1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
	2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
	3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
	4、验证app_id是否为该商户本身。
	*/
	try{
        if(signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

            if(trade_status.equals("TRADE_FINISHED")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            }else if (trade_status.equals("TRADE_SUCCESS")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知
            }

            return DtoUtil.returnSuccessWithMsg("success");

        }else {//验证失败
            return DtoUtil.returnFail("error","验证失败");

            //调试用，写文本函数记录程序运行情况是否正常
            //String sWord = AlipaySignature.getSignCheckContentV1(params);
            //AlipayConfig.logResult(sWord);
        }
    }catch (Exception e){
	    e.printStackTrace();
        return DtoUtil.returnFail("error","未知错误");
	}

    }

}
